package com.venutech.gongan.util;

import com.venutech.gongan.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
public class FileUtils {
    static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    public static void sendImage(HttpServletResponse res, String pathAddress) throws UnsupportedEncodingException {
        File file = new File(pathAddress);
        String fileName = file.getName();

        res.setHeader("content-type", "image/png");
        res.setContentType("image/png");
        byte[] buff = new byte[1024];
        FileInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new FileInputStream(file);
            int readTmp = 0;
            while ((readTmp = bis.read(buff)) != -1) {
                os.write(buff, 0, readTmp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        log.info(String.format("图片发送成功！%s", pathAddress));
    }

    /**
     * 下载文件
     *
     * @param res
     * @param pathAddress
     * @throws UnsupportedEncodingException
     */
    public static void down(HttpServletResponse res, String pathAddress) throws UnsupportedEncodingException {
        File file = new File(pathAddress);
        String fileName = file.getName();

        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso-8859-1"));
        byte[] buff = new byte[1024];
        FileInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new FileInputStream(file);
            int readTmp = 0;
            while ((readTmp = bis.read(buff)) != -1) {
                os.write(buff, 0, readTmp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        log.info("文件下载成功！");
    }

    /**
     * 返回上传文件结果
     *
     * @param status
     * @param url
     * @param map
     * @return
     */
    public static Map<String, Object> result(String status, String url, Map<String, Object> map) {
        Map<String, Object> result = new HashMap<>();
        if (map == null) {
            map = new HashMap<>();
        }
        if (Constants.SUCCESS.equals(status)) {
            if (!map.isEmpty()) {
                result.put("status", status);
                result.put("url", url);
                result.put("code", Constants.CODE_OK);
                result.put("data", map);
                return result;
            }
            result.put("status", status);
            result.put("url", url);
            result.put("code", Constants.CODE_OK);
            result.put("data", map);

        } else {
            result.put("status", status);
            result.put("url", "");
            result.put("code", Constants.CODE_NO);
            result.put("data", map);
        }
        return result;
    }


    public static void downLoadZip(String FilePath, HttpServletResponse response, List<String> list) throws IOException {
        String tmpFileName = "二维码.zip";
        String strZipPath = FilePath + tmpFileName;
        byte[] buffer = new byte[1024 * 100];
        ZipOutputStream zip = null;
        FileInputStream fis = null;
        try {
            zip = new ZipOutputStream(new FileOutputStream(strZipPath));
            for (int i = 0; i < list.size(); i++) {
                File file = new File(list.get(i));
                logger.info("downLoadUnZip:file={}", file.getPath());
                fis = new FileInputStream(file);
                zip.putNextEntry(new ZipEntry(file.getName()));
                //设置压缩文件内的字符编码，不然会变成乱码
                zip.setEncoding("GBK");
                int len;
                // 读入需要下载的文件的内容，打包到zip文件
                while ((len = fis.read(buffer)) > 0) {
                    zip.write(buffer, 0, len);
                }
                zip.closeEntry();
            }
            try {
                zip.flush();
                fis.close();
                zip.close();
            } catch (Exception ignore) {

            }
            downFile(FilePath, response, tmpFileName);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
        }
    }


    private static void downFile(String FilePath, HttpServletResponse response, String str) {
        try {
            String path = FilePath + str;
            File file = new File(path);
            if (file.exists()) {
                InputStream ins = new FileInputStream(path);
                BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面
                OutputStream outs = response.getOutputStream();// 获取文件输出IO流
                BufferedOutputStream bouts = new BufferedOutputStream(outs);
                response.setContentType("text/html;charset=utf-8");
                response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(str, "UTF-8"));// 设置头部信息
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                // 开始向网络传输文件流
                while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
                    bouts.write(buffer, 0, bytesRead);
                }
                bouts.flush();// 这里一定要调用flush()方法
                ins.close();
                bins.close();
                outs.close();
                bouts.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

